package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.usian.admin.feign.ArticleFeign;
import com.usian.admin.feign.WemediaFeign;
import com.usian.admin.mapper.AdChannelMapper;
import com.usian.admin.mapper.AdSensitiveMapper;
import com.usian.admin.service.WemediaNewsAutoScanService;
import com.usian.common.aliyun.GreeTextScan;
import com.usian.common.aliyun.GreenImageScan;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.wemedia.vo.WmNewsVo;
import com.usian.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Log4j2
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private AdSensitiveMapper adSensitiveMapper;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private FastDFSClient fastDFSClient;
    @Autowired
    private GreeTextScan greeTextScan;
    @Autowired
    private AdChannelMapper adChannelMapper;

    @Value("${fdfs.url}")
    private String fileServerUrl;



    //通过文章id   判断文章是否存在
    @Override
    @GlobalTransactional
    public void autoScanByMediaNewsId(Integer id) {
        if (id == null){
            log.error("当前的审核id为空");
            return ;
        }

        //远程调用   根据id查询自媒体信息
        WmNews wmNews = wemediaFeign.findById(id);
        if (wmNews==null){
            log.error("审核的自媒体文章不存在，自媒体的id:{}",id);
            return;
        }

        //文章状态为4（人工审核通过）   保存数据和创建索引
        if (wmNews.getStatus()==4){
            saveAppArticle(wmNews);
            return;
        }


        //文章状态为8    发布时间>当前时间    直接保存数据
        if (wmNews.getStatus() ==8 && wmNews.getPublishTime().getTime()<=System.currentTimeMillis()){
            //保存数据
            saveAppArticle(wmNews);
            return;
        }

        //文章状态为1（待审核）
        if (wmNews.getStatus() ==1){
            //抽取文章内容中的纯文本和图片
            Map<String,Object> contentAndImagesResult = handleTestAndImages(wmNews);
            //文本内容审核
            boolean textScanBoolean = HandleTestScan((String) contentAndImagesResult.get("content"),wmNews);
            if (!textScanBoolean) return;
            //图片审核
            boolean imagesScanBoolean = handleImagesScan((List<String>) contentAndImagesResult.get("images"),wmNews);
            if (!imagesScanBoolean) return;
            //自管理的敏感词审核
            boolean sensitiveScanBoolean = handleSensitive((String) contentAndImagesResult.get("content"),wmNews);
            if (!sensitiveScanBoolean) return;
            //发布时间>当前时间
            if (wmNews.getPublishTime().getTime()>System.currentTimeMillis()){
                //修改当前状态为8
                updateWmNews(wmNews, (short) 8,"审核通过，待发布");
                return;
            }
            //审核通过，将状态改为9   保存文章内容
            saveAppArticle(wmNews);
        }
    }

    //敏感词审核
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = false;
        List<String> allSensitive = adSensitiveMapper.findAllSensitive();
        //初始化敏感词
        SensitiveWordUtil.initMap(allSensitive);
        //文章内容自管理敏感词过滤
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size()>0){
            log.error("敏感词过滤没通过，包含了敏感词：{}",map);
            //有敏感词  没通过
            updateWmNews(wmNews, (short) 2,"文章中有敏感词");
            flag = false;
        }
        return flag;
    }

    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        if (images==null){
            return true;
        }
        boolean flag = true;
        ArrayList<byte[]> imageList = new ArrayList<>();

            try {
                for (String image : images) {
                    String imageName = image.replace(fileServerUrl,"");
                    int index = imageName.indexOf("/");
                    String groupName = imageName.substring(0, index);
                    String imagePath = imageName.substring(index + 1);
                    byte[] imageByte = fastDFSClient.download(groupName, imagePath);
                    imageList.add(imageByte);
                }
                //阿里云图片审核
                Map map = greenImageScan.imageScan(imageList);
                //审核不通过
                if (!map.get("suggestion").equals("pass")){
                    //审核失败
                    if (map.get("suggestion").equals("block")){
                        //修改文章状态    告知审核失败原因
                        updateWmNews(wmNews, (short) 2,"文章中图片有违规");
                        flag = false;
                    }

                    //人工审核
                    if (map.get("suggestion").equals("review")){
                        //修改文章状态    告知审核失败原因
                        updateWmNews(wmNews, (short) 3,"文章图片有不确定因素");
                        flag = false;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                flag = false;
            }

        return flag;
    }

    //文本内容审核
    private boolean HandleTestScan(String content, WmNews wmNews) {
        boolean flag = true;
        try {

            //获取到了文本内容
            Map map = greeTextScan.greeTextScan(content);
            //审核不通过
            if (!map.get("suggestion").equals("pass")){
                //审核失败
                if (map.get("suggestion").equals("block")){
                    updateWmNews(wmNews, (short) 2,"文章内容有敏感词");
                    flag = false;
                }

                //人工审核
                if (map.get("suggestion").equals("review")){
                    updateWmNews(wmNews, (short) 3,"文章内容有不确定的因素");
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }

        return flag;
    }


    //提取文本内容和图片
    private Map<String, Object> handleTestAndImages(WmNews wmNews) {
        //获取文章图文内容
        String content = wmNews.getContent();
        //存储文章内容
        StringBuilder stringBuilder = new StringBuilder();
        //在集合中   存储图片
        List<String> images = new ArrayList<>();
        //转化为jsonArray格式
        List<Map> contestList = JSONArray.parseArray(content,Map.class);
        for (Map map : contestList) {
            if (map.get("type").equals("test")){
                stringBuilder.append(map.get("value"));
            }

            if (map.get("type").equals("test")){
                images.add((String) map.get("value"));
            }
        }
        //判断图片不为空   不为0
        if (wmNews.getImages()!=null && wmNews.getType()!=0){
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("content",stringBuilder.toString());
        resultMap.put("images",images);
        return resultMap;
    }

    //保存数据
    private void saveAppArticle(WmNews wmNews) {
        //保存app文章
        ApArticle apArticle = saveArticle(wmNews);
        //保存app文章配置
        saveArticleConfig(apArticle);
        //保存app文章内容
        saveArticleContent(apArticle,wmNews);

        //修改自媒体文章的状态为9
        updateWmNews(wmNews,(short)9,"审核通过");
    }

    private void updateWmNews(WmNews wmNews, short status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        wemediaFeign.updateWmNews(wmNews);
    }

    //创建app端文章内容信息
    private void saveArticleContent(ApArticle apArticle, WmNews wmNews) {
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());

        articleFeign.saveArticleContent(apArticleContent);

    }


    //创建App端文章配置信息
    private void saveArticleConfig(ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsForward(true);

        articleFeign.saveArticleConfig(apArticleConfig);
    }


    private ApArticle saveArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        //获取文章的标题
        apArticle.setTitle(wmNews.getTitle());
        //获取文章的布局
        apArticle.setLayout(wmNews.getType());
        //获取文章的图片
        apArticle.setImages(wmNews.getImages());
        //获取文章的创建时间
        apArticle.setCreatedTime(new Date());

        //获取作者的信息
        Integer wmUserId = wmNews.getUserId();
        WmUser wmUser = wemediaFeign.findWmUserById(wmUserId);
        if (wmUser!=null){
            String wmUserName = wmUser.getName();
            ApAuthor apAuthor = articleFeign.selectAuthorByName(wmUserName);
            if (apAuthor!=null){
                apArticle.setAuthorId(apAuthor.getId().longValue());
                apArticle.setAuthorName(apAuthor.getName());
            }
        }

        //获取频道信息
        Integer channelId = wmNews.getChannelId();
        AdChannel Channel = adChannelMapper.selectById(channelId);
        if (Channel!=null){
            apArticle.setChannelId(Channel.getId());
            apArticle.setChannelName(Channel.getName());
        }
        return articleFeign.saveArticle(apArticle);
    }

    @Override
    public PageResponseResult findNews(NewsAuthDto dto) {
        //分页查询
        PageResponseResult responseResult =  wemediaFeign.findList(dto);
        //有图片需要显示，需要fasfdfs服务器地址
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult findOne(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2查询数据
        WmNewsVo wmNewsVo = wemediaFeign.findWmNewsVo(id);
        //结构封装
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult updateStatus(Integer type, NewsAuthDto dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = wemediaFeign.findById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.审核没有通过
        if(type.equals(0)){
            updateWmNews(wmNews,(short)2,dto.getMsg());
        }else if(type.equals(1)){
            //4.人工审核通过
            updateWmNews(wmNews,(short)4,"人工审核通过");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
